<?php
/*
*time：2017-02-24
*author:lisp
*/
class scanforgift {
    //扫码关注执行方法
    public function scan_care($param){
        $retVal = Session::init();
       
        $result = array();
        $userName=Session::$user['userName'];
        $customerId = Session::$user['customerId'];
        $userId =  Session::$user['userId'];
        log::write('scan_care'.json_encode(Session::$user));
        log::write('scan_care_param'.json_encode($param));
        $openid = $param->message->fromUserName;
        $qrcode_id = $param->codeId;
        Session::switchCustomer($customerId);
        $user_db = M("user");
        $user_weixin_info_db = M('user_weixin_info');
        $map = array();
        $map['userName'] = $openid;
        $user_info = $user_db->where($map)->find();
        $map_weixin = array();
        $map_weixin['openid'] = $openid;
        $user_weixin_info =  $user_weixin_info_db->where($map_weixin)->find();
        Session::switchCustomer(0);
        $miscanforgift_record_db = M('scanforgift_record');

        $record_info = $miscanforgift_record_db->where('qrcode_id='.$qrcode_id)->find();
        $activityId = $record_info['activityId'];
        $activity_info = scanforgift::get_activity_info($activityId,$customerId);
        $status = $user_info['status'];
        //如果从来没有关注过则添加助力
         $subscribeTime = $user_info['subscribeTime'];
         $subscribe = strtotime($subscribeTime);
         $date_now = time();
         $dvalue = $date_now - $subscribe;
         $unsubscribeTime = $user_info['unsubscribeTime'];
         $jsonstr = $activity_info['jsonstr'];

         $user_map = array();
         $user_map['userId'] = $record_info['userId'];
         $user_info_partake = $user_weixin_info_db->where($user_map)->find();
        if($status == 'scansubscribe' && $dvalue <= 3 && !$unsubscribeTime){
           $update_result = $miscanforgift_record_db->where('qrcode_id='.$qrcode_id)->setInc('care_count',1);
           $count = $record_info['care_count'];
           if($update_result){
              $count++;
           }
           if($count >= $jsonstr['task_count']){
               $first = $jsonstr['finishedTopContent'];
               $keyword1 = $jsonstr['taskName'];
               $keyword2 = '已完成';
               $remark = $jsonstr['finishedBottomContent'];

           }else{
               
               $first = $jsonstr['unfinishedTopContent'];
               $keyword1 = $jsonstr['taskName'];
               $keyword2 = '未完成';
               $remark = $jsonstr['unfinishedBottomContent'];
           }
            $first = str_replace("{partake_nickname}",$record_info['nickname'], $first);
            $first = str_replace("{follow_nickname}",$user_weixin_info['nickname'], $first);

            $task_count = $jsonstr['task_count'];
            $remark = str_replace("{task_count}",$task_count, $remark);
            $remark = str_replace("{follow_count}",$count, $remark);

            // $tplType = 'OPENTM200605630';
            $tplType = 'scanforgift_OPENTM200605630';
            $partake_openid = $user_info_partake['openid'];
            
            $data['first'] = array('value'=> $first,'color'=>"#000000");
            $data['keyword1'] = array('value'=> $keyword1,'color'=>'#000000');
            $data['keyword2'] = array('value'=> $keyword2,'color'=>'#000000');

            $data['remark'] = array('value'=> $remark,"color"=>'#000000');
            $url = C('SERVER_HOST').'call.html?customerId='.$customerId.'&module=scanforgift&method=show&params={"actId":'.$activityId.',"partake_id":'.$record_info['partakeId'].'}';
            $log_data = $data;
            $log_data['partake_openid'] = $partake_openid;
             $log_data['customerId'] = $customerId;
             $log_data['tplType'] = $tplType;
             $log_data['url'] = $url;
             Log::write('scanforgift_notice:'.json_encode($log_data));
            TemplateMessage::send($partake_openid,$customerId,$tplType,$url,$data);
            // $url = '';
            // $url = urlencode($url);
            // $log_data = $data;
            // $log_data['url'] = $url;
            // $log_data['momentsOpenid'] = $momentsOpenid;
            // $log_data['tplType'] = $tplType;
            // $log_data['customerId'] = $customerId;
            // Log::write('comment_notice:'.json_encode($log_data));
           
        }
        $imageTextTitle = $jsonstr['imageTextTitle'];
        $imageTextTitle = str_replace("{partake_nickname}",$record_info['nickname'],$imageTextTitle);
        $imageTextTitle = str_replace("{follow_nickname}",$user_weixin_info['nickname'],$imageTextTitle);
        $imageTextCoverImg = $jsonstr['imageTextCoverImg'];
        $imageTextRemark = $jsonstr['imageTextRemark'];
        $imageTextUrl = $jsonstr['imageTextUrl'];
        $articles = array();
        $article = new stdClass();
        $article->title = urlencode((string)$imageTextTitle);
        $article->url = urlencode((string)$imageTextUrl);
        $article->picurl = urlencode((string)$imageTextCoverImg);
        $article->description = urlencode((string)$imageTextRemark);
        array_push($articles, $article);
        $result = WeixinApi::sendServiceMsg($openid, 'news','',$articles);
        if($result->errcode == 0){
            return true;
        }else{
            return false;
        }
    }

    public function guide($param){
         $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $result = array();
        $userName=Session::$user['userName'];
        $customerId = Session::$user['customerId'];
        $userId =  Session::$user['userId'];;


        $actId=$param->actId;
        $chanelId=$param->chanelId;
        if($actId > 0){
            
              $activity_info = scanforgift::get_activity_info($actId,$customerId);
              $result['activity_info'] = $activity_info;
               $result['code'] = 0;
                $result['openid'] = $userName;
              
                $result['userId'] = $userId;
                
        }else{

            Output::instance()->resultCode(-1,"没有这个活动喔");
            exit;
        }
        
        // {"activity_bg":{"src":"http://oss.mboxone.com/20170301/image/3/1488369034532817.png"},"activity_main":{"src":"http://oss.mboxone.com/20170301/image/3/1488369034374942.png"},"activity_index_img":{"src":"http://oss.mboxone.com/20170301/image/3/1488369034315410.jpg,http://oss.mboxone.com/20170301/image/3/1488369034347122.jpg"},"activty_index_button":{"src":"http://oss.mboxone.com/20170301/image/3/1488369034798097.png"},"activity_submit_button":{"src":"http://oss.mboxone.com/20170301/image/3/1488369034625415.png"},"activity_submit_tip":{"src":"http://oss.mboxone.com/20170301/image/3/1488369034135074.jpg,http://oss.mboxone.com/20170301/image/3/1488369034863193.jpg"},"activity_info_bg":{"src":"http://oss.mboxone.com/20170301/image/3/1488369034387607.png"},"activity_info_submit":{"src":"http://oss.mboxone.com/20170301/image/3/1488369034746508.png"},"activity_join_button":{"src":"http://oss.mboxone.com/20170301/image/3/1488369034417155.png"},"show_share":{"src":"http://oss.mboxone.com/20170227/image/3/1488200864796426.png","title":"show_share_title","description":"show_share_description"}}

        Output::instance()->module('scanforgift',"guide")->object($result);
        exit;
    }
    /*
    *首页
    */
    public function index($param){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $result = array();
        $userName=Session::$user['userName'];
        $customerId = Session::$user['customerId'];
        $userId =  Session::$user['userId'];;


        $actId=$param->actId;
        $chanelId=$param->chanelId;
        if($actId > 0){
            $partake_id = scanforgift::check_join($param);
              $activity_info = scanforgift::get_activity_info($actId,$customerId);
              $result['activity_info'] = $activity_info;
            if($partake_id){
                $result['code'] = 1;
                $result['partake_id'] = $partake_id;
                $param->partake_id = $partake_id;
               // $result['record_info'] = scanforgift::get_record($partake_id);
            }else{
                $result['code'] = 0;
                $result['openid'] = $userName;
              
                $result['userId'] = $userId;
                
            }
        }else{

            Output::instance()->resultCode(-1,"没有这个活动喔");
            exit;
        }
        scanforgift::add_visit($param);
        // {"activity_bg":{"src":"http://oss.mboxone.com/20170301/image/3/1488369034532817.png"},"activity_main":{"src":"http://oss.mboxone.com/20170301/image/3/1488369034374942.png"},"activity_index_img":{"src":"http://oss.mboxone.com/20170301/image/3/1488369034315410.jpg,http://oss.mboxone.com/20170301/image/3/1488369034347122.jpg"},"activty_index_button":{"src":"http://oss.mboxone.com/20170301/image/3/1488369034798097.png"},"activity_submit_button":{"src":"http://oss.mboxone.com/20170301/image/3/1488369034625415.png"},"activity_submit_tip":{"src":"http://oss.mboxone.com/20170301/image/3/1488369034135074.jpg,http://oss.mboxone.com/20170301/image/3/1488369034863193.jpg"},"activity_info_bg":{"src":"http://oss.mboxone.com/20170301/image/3/1488369034387607.png"},"activity_info_submit":{"src":"http://oss.mboxone.com/20170301/image/3/1488369034746508.png"},"activity_join_button":{"src":"http://oss.mboxone.com/20170301/image/3/1488369034417155.png"},"show_share":{"src":"http://oss.mboxone.com/20170227/image/3/1488200864796426.png","title":"show_share_title","description":"show_share_description"}}

        Output::instance()->module('scanforgift',"index")->object($result);
        exit;
    }

    private function add_visit($param){
        $retVal = Session::init();
        $customerId = Session::$user['customerId'];
        $userId =  Session::$user['userId'];
        $fromUserId = $param->fromUserId;

        $actId = $param->actId;
        $partake_id = $param->partake_id;
        $channelId = $param->chanelId;
        Session::switchCustomer(0);

        $activity_visit_db = M('miactivity_visit');
        // if($fromUserId != $userId){
        /*新增获取ip对应的信息*/
        $ipInfo = self::getIp_agent();

        $visit_data = array();
        $visit_data['cid'] = $customerId;
        $visit_data['activityId'] = $actId;
        $visit_data['partakeId'] = $partake_id;
        $visit_data['channelId'] = $channelId;
        $visit_data['userId'] = $userId;
        $visit_data['fromUserId'] = $fromUserId;
        $visit_data['createTime'] = date('Y-m-d H:i:s');
        /*以下数据为新增*/
        $visit_data['ip_address'] = $ipInfo['ip_address'];
        $visit_data['ip_city'] = $ipInfo['city'];
        $visit_data['ip_province'] = $ipInfo['province'];
        $visit_data['user_agent'] = $ipInfo['userAgent'];

        $activity_visit_db->add($visit_data);
        log::write('visit_sql'.$activity_visit_db->_sql());
        // }
    }


    private function get_record($partake_id){
        Session::switchCustomer(0);
        $miscanforgift_record_db = M('scanforgift_record');
       
        $map = array();
        $map['partakeId'] = $partake_id;
        $record_info = $miscanforgift_record_db->where($map)->find();
        if($record_info){
           // $file_path = LOCAL_PIC_PATH.$record_info['img_url'];
           // if(!is_file($file_path)){
                $actId = $record_info['activityId'];
                $userId = $record_info['userId'];
                $customerId = $record_info['cid'];
                $record_result = $record_info['id'];
                $qrImg = $record_info["qrimg"];
                $path= LOCAL_PIC_PATH."scanforgiftcode/";
                $fileName = $customerId.'_'.$actId.'_'.$userId.'_'.$partake_id.'_'.$record_result;
                $activity_info = scanforgift::get_activity_info($actId,$customerId);
                $jsonstr = $activity_info['jsonstr'];
                $qrcodeLocation = $jsonstr['transverseAxis'].'|'.$jsonstr['longitudinalCoordinateAxis'];
                $qrcodeSize = $jsonstr['width'].'*'.$jsonstr['height'];
                $shareImgBg = $jsonstr['shareImgBg'];

                $create_img_result = scanforgift::createImage($path,$fileName,$qrImg,$shareImgBg,$qrcodeLocation,$qrcodeSize);
                log::write('create_img_result'.json_encode($create_img_result));
                $img_url = '/scanforgiftcode/'.$fileName.'.png';

                $record_info['img_url'] = $img_url;
                // $save_data = array();
                // $save_data['img_url'] = $img_url;
                // $update_img_url = $miscanforgift_record_db->where('id='.$record_result)->save($save_data);
         //  }
        }
        return $record_info;

    }
    /*
    *获取参加过此活动的参与编号
    */
    public function check_join($param){
        $retVal = Session::init();
        $customerId = Session::$user['customerId'];
        $userId =  Session::$user['userId'];;

        $actId=$param->actId;
        $chanelId=$param->chanelId;
        // $userId = 22;
        // $partake_id = S('partake_id_'.$customerId.'_'.$actId.'_'.$userId);
//    	if(!$partake_id){
        $map = array();
        $map['userId'] = $userId;
        $map['activityId'] = $actId;
        $map['cid'] = $customerId;
        Session::switchCustomer(0);
        $activity_partake_db = M('miactivity_partake');
        $partake_id = $activity_partake_db->where($map)->getField('id');
        if($partake_id > 0){
            // S('partake_id_'.$customerId.'_'.$actId.'_'.$userId,$partake_id,3500*24);
        }
//    	}

        return $partake_id;
    }


    /*
    *立即参加按钮所对应页面
    */
    public function join_now($param){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $result = array();
        $userName=Session::$user['userName'];
        $customerId = Session::$user['customerId'];
        $userId = Session::$user['userId'];
        $actId=$param->actId;
        $param_partake_id = $param->partake_id;
        if($param_partake_id && $param_partake_id > 0){
            $partake_id = $param_partake_id;
        }else{
            $partake_id = scanforgift::check_join($param);
        }
        
        if($partake_id && $partake_id > 0){
            $result['code'] = 1;
            $result['partake_id'] = $partake_id;
            $result['qcode_info'] = scanforgift::get_record($partake_id);
            $activity_info = scanforgift::get_activity_info($actId,$customerId);
            $result['activity_info'] = $activity_info;
            $result['userId'] =  $userId;
            $param->partakeId = $partake_id;
            if($result['qcode_info']['userId'] != $userId){
                scanforgift::add_visit($param);
            }
           // $result['qcode_info'] = scanforgift::get_qcode_info($param,$activity_info);

        }else{
            $result['code'] = 0;
            $activity_info = scanforgift::get_activity_info($actId,$customerId);
            $result['activity_info'] = $activity_info;
            $result['userId'] =  $userId;
            $result['customerId'] = $customerId;
            $partake_info = scanforgift::save_data($param);
            $partake_id = $partake_info['partakeId'];
            $param->partakeId = $partake_id;
            // $result['record_info'] = scanforgift::save_data($param);
            $result['qcode_info'] = $partake_info;
        }
        Output::instance()->module('scanforgift',"join_now")->object($result);
    }
 




    public function deal_prize($activity_cat_item_list){
        /*
       * 奖项数组
       * 是一个二维数组，记录了所有本次抽奖的奖项信息，
       * 其中id表示中奖等级，prize表示奖品，v表示中奖概率。
       * 注意其中的v必须为整数，你可以将对应的 奖项的v设置成0，即意味着该奖项抽中的几率是0，
       * 数组中v的总和（基数），基数越大越能体现概率的准确性。
       * 本例中v的总和为100，那么平板电脑对应的 中奖概率就是1%，
       * 如果v的总和是10000，那中奖概率就是万分之一了。
       *
       */
        $prize_arr = $activity_cat_item_list;
        /*
         * 每次前端页面的请求，PHP循环奖项设置数组，
         * 通过概率计算函数get_rand获取抽中的奖项id。
         * 将中奖奖品保存在数组$res['yes']中，
         * 而剩下的未中奖的信息保存在$res['no']中，
         * 最后输出json个数数据给前端页面。
         */
        $prize_arr_data = array();
        foreach ($prize_arr as $key => $val) {
            $arr[$val['id']] = $val['rate'];
            $prize_arr_data[$val['id']] = $val;
        }
        $rid = scanforgift::get_rand($arr); //根据概率获取奖项id

        return $prize_arr_data[$rid];

    }
    /*
     * 经典的概率算法，
     * $proArr是一个预先设置的数组，
     * 假设数组为：array(100,200,300，400)，
     * 开始是从1,1000 这个概率范围内筛选第一个数是否在他的出现概率范围之内，
     * 如果不在，则将概率空间，也就是k的值减去刚刚的那个数字的概率空间，
     * 在本例当中就是减去100，也就是说第二个数是在1，900这个范围内筛选的。
     * 这样 筛选到最终，总会有一个数满足要求。
     * 就相当于去一个箱子里摸东西，
     * 第一个不是，第二个不是，第三个还不是，那最后一个一定是。
     * 这个算法简单，而且效率非常 高，
     * 关键是这个算法已在我们以前的项目中有应用，尤其是大数据量的项目中效率非常棒。
     */
    private function get_rand($proArr) {
        $result = '';
        //概率数组的总概率精度
        $proSum = array_sum($proArr);
        //概率数组循环
        foreach ($proArr as $key => $proCur) {
            if($proCur <= 0){
                $result = $key;
            }
            $randNum = mt_rand(1, $proSum);
            if ($randNum <= $proCur) {
                $result = $key;
                break;
            } else {
                $proSum -= $proCur;
            }
        }
        unset ($proArr);
        return $result;
    }

    /*
    *获取活动信息
    */
    private function get_activity_info($actId,$customerId){
        // $activity_info = S('activity_info_'.$actId.'_'.$customerId);
//		if(!$activity_info){
        $retVal = Session::init();
        $userName=Session::$user['userName'];
        $userId = Session::$user['userId'];

        Session::switchCustomer(0);
        $map = array();
        $map['deleted'] = 0;
        $map['fromCustomerId'] = $customerId;
        $activity_info = M("Miactivity")->field('deleted',true)->where($map)->find($actId);

        if($activity_info){
            $jsonstr = json_decode($activity_info['jsonstr'],true);

            $jsonstr['ruleImgs'] = explode(',',$jsonstr['ruleImgs']);

            // $jsonstr['activity_submit_tip']['src'] = explode(',',$jsonstr['activity_submit_tip']['src']);
            $activity_info['jsonstr'] = $jsonstr;
            if($activity_info['accessTag'] && $activity_info['accessTag'] != ''){
                setAccessTags($activity_info['accessTag'],$userName,'scanforgift',$activity_info['id']);
            }

            Session::switchCustomer($customerId);
            $user_map = array();
            $user_map['id'] = $userId;
            $status = M('user')->where($user_map)->getField('status');
            $is_subscribe = (in_array($status, ['subscribe', 'scansubscribe'])) ? 1 : 0;
            $activity_info['is_subscribe'] = $is_subscribe;

        }else{
            Output::instance()->resultCode(-1,"没有这个活动喔");
            return;
        }

        return $activity_info;
    }
    /*
    *检测活动状态
    */
    public  function check($param){
        $retVal = Session::init();
        if(!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $actId=$param->actId;
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $result = $map = array();
        $map = array();
        $map['deleted'] = 0;
        $map['id'] = $actId;
        $map['status'] = 1;
        $map['endTime'] = array('gt',date('Y-m-d H:i:s'));
        $map['startTime'] = array('lt',date('Y-m-d H:i:s'));
        $map['fromCustomerId'] = $customerId;
        $activity_info = M("Miactivity")->field('type,deleted',true)->where($map)->find();


        if($activity_info && is_array($activity_info)){
            if($activity_info['isLimitCount'] == 1){
                if($activity_info['limitCount'] <= $activity_info['partakeCount']){
                    $result['code'] = 0;
                    $result['info'] = '此活动参与人数已达上限，不可参加';
                }else{
                    $result['code'] = 1;
                }
            }else{
                $result['code'] = 1;
            }

        }else{
            $result['code'] = 0;
            $result['info'] = '此活动尚未开始或已结束';
        }

        Output::instance()->module('scanforgift',"check")->object($result);

    }
    /*
    *添加参加活动数据
    */
    public function save_data($param){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $result = array();
        $userName=Session::$user['userName'];
        $customerId = Session::$user['customerId'];
        $actId=$param->actId;

        $activity_info = scanforgift::get_activity_info($actId,$customerId);

        if($activity_info){
            $time_now = date('Y-m-d H:i:s');
            if($activity_info['status'] == 1 && $activity_info['startTime'] < $time_now &&  $activity_info['endTime'] > $time_now){
                if($activity_info['isLimitCount'] == 1){
                    if($activity_info['limitCount'] > $activity_info['partakeCount']){
                        $sql = 'lock table '.C('DB_PREFIX').'miactivity read';
                        M()->execute($sql);
                        $result = scanforgift::deal_data($param,$activity_info);
                        $sql = 'unlock tables';
                        M()->execute($sql);

                    }else{
                        Output::instance()->resultCode(-1,"此活动参与人数已达上限，不可参加");
                        exit;
                        // $result['code'] = 0;
                        // $result['info'] = '此活动参与人数已达上限，不可参加';
                    }
                }else{
                    $result = scanforgift::deal_data($param,$activity_info);
                }

            }else{
                Output::instance()->resultCode(-1,"此活动尚未开始或已结束");
                exit;
                // $result['code'] = 0;
                // $result['info'] = '';
            }

        }else{
            $result['code'] = 0;
            $result['info'] = '活动信息不存在';
        }
        return $result;
        //Output::instance()->module('scanforgift',"save_data")->object($result);
    }
    public function get_prize_item($param){

        Session::switchCustomer(0);
        $miscanforgift_item_db = M('miscanforgift_item');
        $map = $member_map = array();
        $map = 'activityId='.$param->actId.' and ((count > 0 and count > has_use) || count <= 0) and deleted = 0';
        $activity_cat_item_list = $miscanforgift_item_db->where($map)->select();

        if($activity_cat_item_list && $activity_cat_item_list){
            $prize_item = scanforgift::deal_prize($activity_cat_item_list);
        }else{
            Output::instance()->resultCode(-1,"还没有给这个活动设置奖项或活动奖项已被抽完");
            exit;
        }
        return $prize_item;
    }
    /*
    *具体处理参加活动的数据
    */
    public function deal_data($param,$activity_info){

        $partakeCount = $activity_info['partakeCount'];
        $retVal = Session::init();
        $result = array();
        $userName=Session::$user['userName'];
        $customerId = Session::$user['customerId'];
        // $customerId = $customerId?$customerId:'0';
        $userId = Session::$user['userId'];
        // $userId = $userId?$userId:'0';
        if($userId && $userId > 0){
            $cid = $customerId;
            $fromUserId = $param->fromUserId;
            $fromUserId = $fromUserId?$fromUserId:'0';

            $channelId = $param->chanelId;
            $channelId = $channelId?$channelId:'0';


            $telephone = $param->telephone;
            $real_name = $param->real_name;
            $id_card = $param->id_card;
            $actId=$param->actId;
            $activityId = $actId;

            Session::switchCustomer(0);


            $activity_partake_db = M('miactivity_partake');

            $activity_db = M('miactivity');
            $partake_map = array();
            $partake_map['cid'] = $cid;
            $partake_map['userId'] = $userId;
            $partake_map['activityId'] = $activityId;
            $createTime = date('Y-m-d H:i:s');
            $count = $activity_partake_db->where($partake_map)->count();
            if($count <= 0){

                // $prize_item =  scanforgift::get_prize_item($param);

                /*新增获取ip对应的信息*/
                $ipInfo = self::getIp_agent();

                $activity_partake_db->startTrans();
                $partake_data = $photo_share_data = array();
                $partake_data['cid'] = $cid;
                $partake_data['userId'] = $userId;
                $partake_data['fromUserId'] = $fromUserId;
                $partake_data['activityId'] = $activityId;
                $partake_data['channelId'] = $channelId;
                $partake_data['createTime'] = $createTime;
                /*以下数据为新增*/
                $partake_data['ip_address'] = $ipInfo['ip_address'];
                $partake_data['ip_city'] = $ipInfo['city'];
                $partake_data['ip_province'] = $ipInfo['province'];
                $partake_data['user_agent'] = $ipInfo['userAgent'];

                $partake_result = $activity_partake_db->add($partake_data);
                $update_partakeCount = false;
                if($partake_result){
                    $update_map = array();
                    $update_map['fromCustomerId'] = $customerId;
                    $update_map['id'] = $activityId;
                    $partakeCount = intval($partakeCount) + 1;
                    $update_data = array();
                    $update_data['partakeCount'] = $partakeCount;
                    $update_partakeCount = $activity_db->where($update_map)->save($update_data);
                }
                $record_result = false;
                if($partake_result&&$partake_result>0){
                    $param->partakeId = $partake_result;

                    $record_result_return = scanforgift::deal_item($activity_info,$param);
                }
                $record_result = $record_result_return['code'];
                $record_result = $record_result<=0?false:true;
                if($partake_result&&$record_result&&$update_partakeCount){
                    $activity_partake_db->commit();
                    $result['code'] = 1;
                    $result['partakeId'] = $partake_result;
                    $result['img_url'] = $record_result_return['img_url'];
                    // $record_info  = array();
                    // $record_info['id'] = $record_result;
                    // $record_info['item_info'] = $prize_item;
                    // $result['item_info'] = $prize_item;
                    // $result['userId'] = $userId;
                }else{
                    $activity_partake_db->rollback();
                    $result['activity_partake_sql'] = $activity_partake_db->_sql();
                    $result['activity_sql'] = $activity_db->_sql();
                    //$result['miscanforgift_record_db_sql'] = $activity_photo_share_db->_sql();
                    $result['code'] = 0;
                    if(!$partake_result){
                        $error = $activity_partake_db->getError();
                    }elseif(!$update_partakeCount){
                        $error = $activity_db->getError();
                    }else{
                        $error = '发生未知sql错误';
                    }
                    $error = $error?$error:"发生未知错误";
                    $result['info'] = $error;
                }

            }else{
                $result['code'] = 0;
                $result['info'] = '你已经参加过本次活动';
            }
        }else{
            $result['code'] = 0;
            $result['info'] = '用户编号不合法';
        }
        return $result;

    }
    public function update_record($param){

        $retVal = Session::init();
        $customerId = Session::$user['customerId'];
        $userId =  Session::$user['userId'];
        $openid = Session::$user['userName'];
        $result = array();
        $partake_id = $param->partake_id;
        $telephone = $param->telephone;
        $real_name = $param->real_name;
        $province = $param->province;
        $city = $param->city;
        $area = $param->area;
        $address = $param->address;
        // $id_card = $param->id_card;
        Session::switchCustomer(0);
        $miscanforgift_record_db = M('scanforgift_record');
        $count = 0;
        $actId = $param->actId;
        // if(isset($id_card)&&$id_card != ''){
        //     $has_gain = array();
        //     $has_gain['id_card'] = $id_card;
        //     $has_gain['gain_status'] = 1;
        //     $has_gain['cid'] = $customerId;
        //     $has_gain['activityId'] = $actId;
        //     $count = $miscanforgift_record_db->where($has_gain)->count();
        // }
        if($count <= 0){
            $update_map['partakeId'] = $partake_id;
            $save_data['telephone'] = $telephone;
            $save_data['real_name'] = $real_name;
            $save_data['province'] = $province;
            $save_data['city'] = $city;
            $save_data['area'] = $area;
            $save_data['address'] = $address;
            $save_data['gain_status'] = 1;
            $update_result = $miscanforgift_record_db->where($update_map)->save($save_data);
            if($update_result){
                $result['code'] = 1;
                $result['info'] = '领取成功';
            }else{
                $result['code'] = 0;
                $result['info'] ='领取失败';
            }
        }else{
            $result['code'] = 0;
            $result['info'] ='当前身份证号已经参加过活动';
        }
        // $update_map = $save_data = array();
        // $update_map['partakeId'] = $partake_id;
        // $save_data['telephone'] = $telephone;
        // $save_data['real_name'] = $real_name;
        // $save_data['id_card'] = $id_card;
        // $save_data['gain_status'] = 1;
        // $update_result = $miscanforgift_record_db->where($update_map)->save($save_data);
        // if($update_result){
        // 	$result['code'] = 1;
        // 	$result['info'] = '领取成功';
        // }else{
        // 	$result['code'] = 0;
        // 	$result['info'] ='领取失败';
        // }
        Output::instance()->module('scanforgift',"update_record")->object($result);

    }
    private function deal_item($activity_info,$param){

        $result = array();
        $retVal = Session::init();
        $customerId = Session::$user['customerId'];
        $userId =  Session::$user['userId'];
        $openid = Session::$user['userName'];

        $actId=$param->actId;
        $chanelId = $param->chanelId;

        $return = $member_map = $item_map= array();
        $member_map['activityId'] = $actId;
        $member_map['userId'] = $userId;
        


        $coupon_result = true;
        $crystal_coins_result = true;
        $redbag = true;
        $dec_itme_count = true;

        $prize_status = 0;
        $info = '';
        Session::switchCustomer($customerId);
        $user_map = array();
        $user_map['userId'] = $userId;
        $user_info = M('user_weixin_info')->field('nickname,headimgurl')->where($user_map)->find();
        Session::switchCustomer(0);
        $miscanforgift_record_db = M('scanforgift_record');
       

        // if(($item['count'] > 0&&$item['count'] > $item['has_use']) || $item['count'] <= 0){
        //     $item_map['id'] = $item['id'];
        //     $dec_itme_count = $miscanforgift_item_db->where($item_map)->setInc('has_use',1);
        // }
        $record_data = array();
        $createTime = date('Y-m-d H:i:s');
        $record_data['createTime'] = $createTime;
        $record_data['userId'] = $userId;
        $record_data['nickname'] = $user_info['nickname'];
        $record_data['headimgurl'] = $user_info['headimgurl'];
        $record_data['activityId'] = $actId;
        $record_data['partakeId'] = $param->partakeId;
       
        $record_data['goods_type'] = $item['goods_type'];
        $record_data['prize_status'] = $prize_status;
       
        $record_data['channelId'] = $chanelId;
        $record_data['cid'] = $customerId;
        $miscanforgift_record_db->startTrans();
        $record_result = $miscanforgift_record_db->add($record_data);

        if($record_result){


            $qrType = QR_SCENE;
            $data = QRCode::add("扫码送礼" .$user_info['nickname'].$record_result, $record_result,"scanforgift", $record_result, "scan_care",$qrType, '', '', $customerId);
            // var_dump($data);
            // exit;
            $qrImg = $data["img"];
            $path= LOCAL_PIC_PATH."scanforgiftcode/";
            $fileName = $customerId.'_'.$actId.'_'.$userId.'_'.$param->partakeId.'_'.$record_result;
            $jsonstr = $activity_info['jsonstr'];
            $qrcodeLocation = $jsonstr['transverseAxis'].'|'.$jsonstr['longitudinalCoordinateAxis'];
            $qrcodeSize = $jsonstr['width'].'*'.$jsonstr['height'];
            $shareImgBg = $jsonstr['shareImgBg'];

            $create_img_result = scanforgift::createImage($path,$fileName,$qrImg,$shareImgBg,$qrcodeLocation,$qrcodeSize);
            log::write('create_img_result'.json_encode($create_img_result));
            $img_url = '/scanforgiftcode/'.$fileName.'.png';
            $result['code'] = 1;
            $result['img_url'] = $img_url;
            $save_data = array();
            $save_data['img_url'] = $img_url;
            $save_data['qrimg'] = $qrImg;
            $save_data['qrcode_id'] = $data['id'];
            $update_img_url = $miscanforgift_record_db->where('id='.$record_result)->save($save_data);
            
            //return $record_result;
        }
        if($record_result&&$update_img_url){
            $miscanforgift_record_db->commit();
        }else{
            $miscanforgift_record_db->rollback();
            $result['code'] = 0;
            $result['info'] = $miscanforgift_record_db->_sql();
            
        }
        return $result;
    }

      private function createImage($path,$fileName,$qrImg,$bgImgUrl,$location,$size){
        $data = array();
        $data['path'] = $path;
        $data['fileName'] = $fileName;
        $data['qrImg'] = $qrImg;
        $data['bgImgUrl'] = $bgImgUrl;
        $data['location'] = $location;
        $data['size'] = $size;

        log::write('createImage'.json_encode($data));
        $fname="$fileName.png";
        if(!file_exists($path)){
            mkdir ($path);
        }
        $fileName=$path . "$fname";
        $img=self::curls($bgImgUrl);
        $img=imagecreatefromstring($img);
        if(!$img) {
            $out1 = new stdClass();
            $out1->code=1;
            $out1->msg="背景图片获取错误，请重试";
            return $out1;
        }
        $imgWidth=imagesx($img);
        $imgHeight=imagesy($img);
        $qrImg=self::curls($qrImg);
        $qrImg=imagecreatefromstring($qrImg);
        if(!$qrImg) {
            $out1=new StdClass();
            $out1->code=1;
            $out1->msg="二维码生成错误，请重试";
            return $out1;
        }
        $qrImgWidth=imagesx($qrImg);
        $qrImgHeight=imagesy($qrImg);
        if($size){
            $size = explode("*",$size);
            $sizeW = $size[0];
            $sizeH = $size[1];
        }else{
            $sizeW=220;
            $sizeH=220;
        }
        if($location){
            $location = explode("|",$location);
            $qrImgLeft=$location[0];
            $qrImgTop=$location[1];
        }else{
            $qrImgLeft=$imgWidth/2-110;
            $qrImgTop = $imgHeight/2-110;
        }
        imagecopyresampled($img,$qrImg,$qrImgLeft,$qrImgTop,0,0,$sizeW,$sizeH,$qrImgWidth,$qrImgHeight);
        imagejpeg($img,$fileName);
        imagedestroy($img);
    }
      public function curls($url, $timeout = '10'){
        // 1. 初始化
        $ch = curl_init();
        // 2. 设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        // 3. 执行并获取HTML文档内容
        $info = curl_exec($ch);
        // 4. 释放curl句柄
        curl_close($ch);

        return $info;
    }

    /*
    *晒图页面数据接口
    */
    public function show($param){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $result = array();
        $userName=Session::$user['userName'];
        $customerId = Session::$user['customerId'];
        $userId = Session::$user['userId'];
        $actId=$param->actId;
        $partake_id = $param->partake_id;
        $record_info = scanforgift::get_record($partake_id);
        if($record_info){
            $result['code'] = 1;
            $result['record_info'] = $record_info;
            $activity_info = scanforgift::get_activity_info($actId,$customerId);
            $result['activity_info'] = $activity_info;
            $result['userId'] = $userId;
            if($userId != $record_info['userId']){
                 scanforgift::add_visit($param);
            }
        }else{
            $result['code'] = 0;
            $result['info'] = '不存在记录';
        }


// 		$channelId = $param->chanelId;
// 		$fromUserId = $param->fromUserId;

// 		$partake_id_self = scanforgift::check_join($param);
// 		if($partake_id_self &&$partake_id_self > 0){
// 			$result['code'] = 1;
// 			$result['partake_id'] = $partake_id_self;
// 		}
// 		$activity_info = scanforgift::get_activity_info($actId,$customerId);
// 		Session::switchCustomer(0);
// 		$activity_photo_share_db = M('miactivity_photo_share');
// 		$activity_visit_db = M('miactivity_visit');


// 		if($partake_id && $partake_id > 0){
// 			if($fromUserId != $userId){
// 				/*新增获取ip对应的信息*/
// 				$ipInfo = self::getIp_agent();

// 				$visit_data = array();
// 				$visit_data['cid'] = $customerId;
// 				$visit_data['activityId'] = $actId;
// 				$visit_data['partakeId'] = $partake_id;
// 				$visit_data['channelId'] = $channelId;
// 				$visit_data['userId'] = $userId;
// 				$visit_data['fromUserId'] = $fromUserId;
// 				$visit_data['createTime'] = date('Y-m-d H:i:s');
// 				/*以下数据为新增*/
// 				$visit_data['ip_address'] = $ipInfo['ip_address'];
// 				$visit_data['ip_city'] = $ipInfo['city'];
// 				$visit_data['ip_province'] = $ipInfo['province'];
// 				$visit_data['user_agent'] = $ipInfo['userAgent'];

// 				$activity_visit_db->add($visit_data);
// 			}
// 			$map = array();
// 			$map['partakeId'] = $partake_id;
// 			// $map['']
// 			// $map['deleted'] = 0;
// //            $photo_share_info = S('photo_share_info_'.$customerId.'_'.$actId.'_'.$partake_id);
// //			if(!$photo_share_info){
// 			$photo_share_info = $activity_photo_share_db->field('name,phone,createTime,picUrls,partakeId')->where($map)->find();
// //                S('photo_share_info_'.$customerId.'_'.$actId.'_'.$partake_id,$photo_share_info,3600*24);
// //			}

// 			if($photo_share_info){
// 				$photo_share_info['picUrls'] = explode(',', $photo_share_info['picUrls']);
// 				$result['photo_share_info'] = $photo_share_info;

// 				// $visit_map  = array();
// 				$visit_map = ' EXISTS(select 1 from '.C('DB_PREFIX').'miactivity_visit b where a.userId=b.userId and b.cid = '.$customerId.' and b.partakeId = '.$partake_id.' and activityId = '.$actId.' )';
// 				$visit_map = ' a.userId in (select distinct userId from '.C('DB_PREFIX').'miactivity_visit b where b.cid = '.$customerId.' and b.partakeId = '.$partake_id.' and activityId = '.$actId.' )';
// 				// $visit_map['1'] = array('exp',$where);
// 				// $visit_map['partakeId'] = $partake_id;
// 				// $visit_map['cid'] = $customerId;
// 				// $visit_map['activityId'] = $actId;
// 				Session::switchCustomer($customerId);
// 				$user_weixin_info_db = M('user_weixin_info');
// 				$visit_list = $user_weixin_info_db->alias('a')
// 				->field('a.userId,a.nickname,a.headimgurl')
// 				->where($visit_map)
// 				->select();
// 				// $sql = 'select a.* from '.C('DB_PREFIX').$customerId.'_user_weixin_info a where exists(select 1 from B b where a.id=b.id)';
// 				// $visit_list = $activity_visit_db->alias('a')
// 				// ->join('left join wx_'.$customerId.'_user_weixin_info b on a.userId=b.userId')
// 				// ->field('a.userId,b.nickname,b.headimgurl')
// 				// ->distinct(true)
// 				// ->where($visit_map)->select();

// 			    // $result['sql'] = $activity_visit_db->_sql();
// 				$result['visit_list'] = $visit_list;
// 				$result['visit_count'] = count($visit_list);

// 				$result['activity_info'] = $activity_info;
// 				$result['userId'] =  $userId;

// 			}else{
// 				$result['code'] = 0;
// 				$result['info'] = '参加活动的信息不存在';
// 			}

// 		}else{
// 			$result['code'] = 0;
// 			$result['info'] = '参数不全';
// 		}

        Output::instance()->module('scanforgift',"show")->object($result);

    }

    /*
    *测试
    */
    public function test($param){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $result = array();
        $userName=Session::$user['userName'];
        $customerId = Session::$user['customerId'];
        Output::instance()->module('scanforgift',"test")->object($result);
    }

    /**
     * 获取用户的ip以及user_agent信息
     * @return array
     */
    protected  static function getIp_agent(){
        $ipInfo = array();
        if($_SERVER['HTTP_HTTP_X_REAL_IP']){
            //nginx 代理模式下，获取客户端真实IP
            $realIp = $_SERVER['HTTP_HTTP_X_REAL_IP'];
        }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            //客户端的ip
            $realIp = $_SERVER['HTTP_CLIENT_IP'];
        }elseif (isset($_SERVER['HTTP_HTTP_X_FORWARDED_FOR'])) {
            //浏览当前页面的用户计算机的网关
            $arr = explode(',', $_SERVER['HTTP_HTTP_X_FORWARDED_FOR']);
            $pos = array_search('unknown',$arr);
            if(false !== $pos) unset($arr[$pos]);
            $realIp = trim($arr[0]);
        }elseif (isset($_SERVER['REMOTE_ADDR'])) {
            //浏览当前页面的用户计算机的ip地址
            $realIp = $_SERVER['REMOTE_ADDR'];
        }else{
            $realIp=$_SERVER['REMOTE_ADDR'];
        }
        $userAgent = $_SERVER['HTTP_USER_AGENT'];
        $realIpInt = bindec(decbin(ip2long($realIp)));

        //查询ip对应的地址信息
        if($realIp){
            $cid = Session::$user['customerId'];
            Session::switchCustomer(0);
            $ipInfo_table = M('ip_info');

            $map = array();
            $map['start_ip_int'] = array('elt',$realIpInt);
            $map['end_ip_int'] = array('egt',$realIpInt);
            $result = $ipInfo_table->where($map)->find();
            if($result){
                $ipInfo['province'] = $result['province'];
                $ipInfo['city'] = $result['city'];
            }else{
                Log::write('客户端ip信息----:'.print_r($_SERVER, true));
                Log::write('查询ip信息-----'.$ipInfo_table->getLastSql());
            }
            Session::switchCustomer($cid);
        }

        $ipInfo['ip_address'] = $realIp;
        $ipInfo['userAgent'] = $userAgent;
        return $ipInfo;
    }
}